package com.panopset.java;

import java.io.File;

import com.panopset.compat.Strings;
import com.panopset.io.Directory;
import com.panopset.io.FileRewriter;

/**
 * Format Java source files so that:
 * <ul>
 * <li>
 * Empty brackets have a space between them.</li>
 * <li>
 * Tabs are replaced with 4 spaces.</li>
 * <li>
 * Trailing blanks are trimmed.</li>
 * <li>
 * Source file ends with a crlf.</li>
 * </ul>
 * 
 * @author Karl Dinwiddie
 * 
 */
public final class FormatSource implements Directory.Processor {

	/**
	 * Format all the Java classes specified in files, or recursively in
	 * directories, specified in args.
	 * 
	 * @param args
	 *            Files and/or directories that are to have trailing spaces
	 *            removed, tabs replaced by 4 spaces, and CRLF at the end of the
	 *            file.
	 */
	public static void main(final String... args) {
		new Directory(new FormatSource()).process(args);
	}

	@Override
	public void process(final File file) {
		String ext = new Strings().getExtension(file.getName());
		if (!".java".equals(ext)) {
			return;
		}
		new FileRewriter(new FileRewriter.LineProcessor() {

			@Override
			public String process(String line) {
				return new Strings().trimEnd(line.replace("\u0009", "    ")
						.replace("{\u0020", "{"));
			}

		}).process(file);
	}
}
